# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools, _
from odoo.exceptions import ValidationError, Warning
import datetime
from dateutil.relativedelta import relativedelta


class WorkOrderSave(models.Model):

    _inherit = "tyibs.er.work.order.save"

    @api.multi
    def write(self, vals):
        # 归档时生成风险评测事件记录
        res = super(WorkOrderSave, self).write(vals)
        event_ref_id = "lift_risk.tyibs_risk_event_category_trap"
        if self.response_level != '1':
            # 一级响应失败
            event_ref_id = "lift_risk.tyibs_risk_event_category_trap_response_failed"
        if vals.get("state", False) == "archive":
            # 如果是归档
            self.env["tyibs.risk.event.line"].create({
                "lift_id": self.lift_id.id,
                "event_category_id": self.env.ref(event_ref_id).id,
                "res_model": self._name,
                "res_id": self.id
            })
        return res


class WorkOrderRepair(models.Model):
    """
    报修生成风险监测事件
    """
    _inherit = "tyibs.er.work.order.repair"

    @api.model
    def create(self, vals):
        res = super(WorkOrderRepair, self).create(vals)
        self.env["tyibs.risk.event.line"].create({
            "lift_id": res.lift_id.id,
            "event_category_id": self.env.ref("lift_risk.tyibs_risk_event_category_repairs").id,
            "res_model": self._name,
            "res_id": res.id
        })
        return res


class WorkOrderCompliant(models.Model):
    """
    投诉生成风险监测事件
    """
    _inherit = "tyibs.er.work.order.compliant"

    @api.model
    def create(self, vals):
        res = super(WorkOrderCompliant, self).create(vals)
        self.env["tyibs.risk.event.line"].create({
            "lift_id": res.lift_id.id,
            "event_category_id": self.env.ref("lift_risk.tyibs_risk_event_category_complain").id,
            "res_model": self._name,
            "res_id": res.id
        })
        return res


class WorkOrder(models.Model):
    """
    维保异常生成风险监测事件
    """
    _inherit = "tyibs.main.work.order"

    @api.model
    def create(self, vals):
        res = super(WorkOrder, self).create(vals)
        event_ref_id = ""
        if res.over_due_state == 'over_due_has_main':
            # 超期维保
            event_ref_id = "lift_risk.tyibs_risk_event_category_over_due_main"
        elif res.over_due_state == 'over_due_not_main':
            # 超期未维保
            event_ref_id = "lift_risk.tyibs_risk_event_category_over_due_not_main"
        if event_ref_id:
            self.env["tyibs.risk.event.line"].create({
                "lift_id": res.lift_id.id,
                "event_category_id": self.env.ref(event_ref_id).id,
                "res_model": self._name,
                "res_id": res.id
            })
        return res
